package com.san.metadata.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.san.base.controller.BaseController;
import com.san.common.annotation.Log;
import com.san.common.utils.Constant;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.metadata.domain.ColumnDTO;
import com.san.metadata.domain.OperationJobDO;
import com.san.metadata.domain.TableDTO;
import com.san.metadata.domain.OperationDO;
import com.san.metadata.service.OperationJobService;
import com.san.metadata.service.ManageMetadataService;
import com.san.metadata.service.OperationMetadataService;
import com.san.metadata.service.TechnicalMetadataService;
import com.san.metadata.vo.OperationJobVO;

/**
 * 作业管理业务控制类
 */
@Controller
@RequestMapping("/md/job")
public class OperationJobController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(OperationJobController.class);
	
	/**
	 * 本功能地址前缀
	 */
	private static final String PREFIX = "metadata/operationJob";
	
	@Autowired
	private OperationMetadataService operationService;
	
	@Autowired
	private TechnicalMetadataService technicalService;
	
	@Autowired
	private ManageMetadataService manageService;
	
	@Autowired
	private OperationJobService jobService;

	@GetMapping("view/{operationId}")
	@Log("访问任务管理")
	@RequiresPermissions("md:job:view")
	String view(Model model, @PathVariable("operationId") Long operationId) {
		OperationDO operationDO = operationService.getById(operationId);
		model.addAttribute("operationId", operationId);
		int operationType = 0;
		int operationStatus = 0;
		if (null != operationDO) {
			operationType = operationDO.getOperationType();
			operationStatus = operationDO.getStatus();
		}
		model.addAttribute("operationType", operationType);
		model.addAttribute("operationStatus", operationStatus);
		return PREFIX + "/view";
	}

	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		if (null == params.get("operationId")) {
			return new PageUtils(new ArrayList<OperationJobDO>(), 0);
		}
		// 查询列表数据
		Query query = new Query(params);
		List<OperationJobDO> jobList = jobService.list(query);
		int total = jobService.count(query);
		PageUtils pageUtils = new PageUtils(jobList, total);
		return pageUtils;
	}

	@GetMapping("/add/{operationId}")
	@Log("访问任务管理新增页面")
	@RequiresPermissions("md:job:add")
	String add(@PathVariable("operationId") Long operationId, Model model) {
		model.addAttribute("operationId", operationId);
		return PREFIX + "/add";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@Log("新增任务")
	@RequiresPermissions("md:job:add")
	@PostMapping("/save")
	public R save(OperationJobVO jobVO) {
		try {
			if (null == jobVO.getPriority()) {
				jobVO.setPriority(5);
			}
			
			jobVO.setCreateUserId(getUserId());
			if (jobService.save(jobVO) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("任务保存失败",e);
		}
		return R.error();
	}

	@GetMapping("/edit/{id}")
	@Log("访问任务管理编辑页面")
	@RequiresPermissions("md:job:edit")
	String edit(@PathVariable("id") Long id, Model model) {
		OperationJobDO jobDO = jobService.getById(id);
		String columnRelation = jobDO.getColumnRelation();
		
		List<ColumnDTO> listColumns = new ArrayList<ColumnDTO>();
		try {
			if (Constant.META_TYPE_TECHNICAL == jobDO.getTargetMetaType()) {
				listColumns = technicalService.listTechnicalColumns(jobDO.getTargetTable());
			} else if (Constant.META_TYPE_MANAGE == jobDO.getTargetMetaType()) {
				listColumns = manageService.listManageColumns(jobDO.getTargetTable());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (null != columnRelation && !"".equals(columnRelation)) {
			JSONArray columns = JSONArray.parseArray(columnRelation);
			for (int i = 0;i < columns.size(); i ++) {
				JSONObject obj = (JSONObject)columns.get(i);
				String tc = obj.getString("tc");
				obj.put("desc",getColumnComment(listColumns,tc));
			}
			jobDO.setColumnRelation(columns.toJSONString());
		}
		model.addAttribute("jobDO", jobDO);
		return PREFIX + "/edit";
	}
	
	public String getColumnComment(List<ColumnDTO> listColumns,String columnName) {
		String comment = "";
		if (null != columnName) {
			for (ColumnDTO columnDTO : listColumns) {
				if (columnName.equals(columnDTO.getColumnName())) {
					comment = null == columnDTO.getColumnComment() ? "" : columnDTO.getColumnComment();
				}
			}
		}
		
		return comment;
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@Log("更新任务")
	@PostMapping("/doEdit")
	@RequiresPermissions("md:job:edit")
	public R doEdit(OperationJobVO jobVO) {
		try {
			if (null == jobVO.getPriority()) {
				jobVO.setPriority(5);
			}
			jobService.doEdit(jobVO);
		} catch (Exception e) {
			logger.error("任务更新失败",e);
		}
		return R.ok();
	}

	/**
	 * 删除
	 */
	@Log("删除作业")
	@PostMapping("/remove")
	@RequiresPermissions("md:job:remove")
	@ResponseBody
	public R remove(Long id) {
		try {
			if (jobService.remove(id) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("任务删除失败",e);
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@Log("批量删除作业")
	@PostMapping("/batchRemove")
	@RequiresPermissions("md:job:batchRemove")
	@ResponseBody
	public R batchRemove(@RequestParam("ids[]") Long[] ids) {
		try {
			jobService.batchRemove(ids);
		} catch (Exception e) {
			logger.error("任务批量删除失败",e);
		}

		return R.ok();
	}
	
	@GetMapping("/getTable/{type}")
	@ResponseBody
	public List<TableDTO> getTable(@PathVariable("type") Long type) {
		List<TableDTO> list = new ArrayList<TableDTO>();
		try {
			if (Constant.META_TYPE_TECHNICAL == type.longValue()) {
				return technicalService.listTechnicalTable();
			} else if (Constant.META_TYPE_MANAGE == type.longValue()) {
				return manageService.listManageTable();
			}
			
		} catch (Exception e) {
			logger.error("获取元数据表失败",e);
		}

		return list;
	}
	
	@GetMapping("/getColumn/{type}/{tableId}")
	@ResponseBody
	public List<ColumnDTO> getColumn(@PathVariable("type") Long type,@PathVariable("tableId") Long tableId) {
		List<ColumnDTO> list = new ArrayList<ColumnDTO>();
		try {
			if (Constant.META_TYPE_TECHNICAL == type.longValue()) {
				return technicalService.listTechnicalColumns(tableId);
			} else if (Constant.META_TYPE_MANAGE == type.longValue()) {
				return manageService.listManageColumns(tableId);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}
}
